package com.sptpc.learnspring.service;


import com.sptpc.learnspring.model.Category;
import com.sptpc.learnspring.repository.CategoryRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class CategoryService {
    @Autowired
    private CategoryRepository categoryRepository;


//    插入语句：新建一个分类
    public Category saveCategory(String name) {
        return categoryRepository.save(Category.builder()
                                .name(name).build());
    }


//    查询语句：查询所有分类
    public List<Category> findALl() {
//
//                                          sort按照某一顺序进行排序
        return categoryRepository.findAll(Sort.by(Sort.Direction.DESC,"createTime"));
    }


//    查询语句：查找某一分类
    public Category findOne(String name) {
        ExampleMatcher matcher = ExampleMatcher.matching()
                .withIgnoreCase("name").withIgnoreNullValues();

        Optional<Category> category =  categoryRepository
                .findOne(Example.of(Category.builder().name(name).build(),matcher));
        if (category.isPresent()) {
            return category.get();
        }else {
            return null;
        }
    }


//   查询语句：查询某一分类，使用自创建sql语句
    public Category findOneT(String name) {
//                                                          自动创建sql语句通过By
        Optional<Category> category = categoryRepository.findCategoryByNameLike(name);
        if (category.isPresent()) {
            return category.get();
        }else {
            return null;
        }
    }


//    更新语句：更新某一分类
    public Category update(long id, String newName) {
        Optional<Category> category = categoryRepository.findById(id);
        if (category.isPresent()) {
            Category oldCatgory = category.get();
            oldCatgory.setName(newName);
//                                     自动进行判断是否存在，执行不同语句
            return categoryRepository.saveAndFlush(oldCatgory);
        }else {
            return null;
        }
    }

    //    删除语句:通过id删除
    public boolean delete(long id) {
        try {
            categoryRepository.deleteById(id);
            return true;
        } catch (Exception e) {
            return false;
        }
    }
}
